package rabbitmq.direct;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName Consumer2
 * @Description TODO
 * @Author ZJX
 * @Date 2025/1/7 22:06
 * @Version 1.0
 **/
public class Consumer2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //        1. 创建连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

//        2. 创建 channel
        Channel channel = connection.createChannel();

//        3. 声明队列
        channel.queueDeclare(Constants.DIRECT_QUEUE2,true,false,false,null);

//        4. 消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            /**
             * handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
             * - consumerTag: 消费者标签，用于标识当前消费者。
             * - envelope: 消息的信封信息，包含交换机、路由键等。
             * - properties: 消息的属性信息（如头部信息）。
             * - body: 消息内容，字节数组形式。
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到信息: " + new String(body));
            }
        };
        channel.basicConsume(Constants.DIRECT_QUEUE2,true,consumer);
    }
}
